package com.pansky.crm.common.mybatisplus;

import java.io.Serializable;
import java.util.Optional;

/**
 * @author ：zhouzhiyong
 * @date ：Created in 2021/2/22 15:44
 * @description：ApiResult
 */

public class ApiResult<T> implements Serializable {
    private long code;
    private String msg;
    private T data;

    public ApiResult(IErrorCode errorCode) {
        errorCode = (IErrorCode) Optional.ofNullable(errorCode).orElse(BaseErrorCode.FAILED);
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
    }

    public ApiResult() {
    }

    public static <T> ApiResult<T> ok() {
        return ok(null);
    }

    public static <T> ApiResult<T> ok(T data) {
        BaseErrorCode aec = BaseErrorCode.SUCCESS;
        return restResult(data, aec);
    }

    public static <T> ApiResult<T> failed(String msg) {
        return restResult(null, BaseErrorCode.FAILED.getCode(), msg);
    }

    public static <T> ApiResult<T> failed(IErrorCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> ApiResult<T> restResult(T data, IErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    private static <T> ApiResult<T> restResult(T data, long code, String msg) {
        ApiResult<T> apiResult = new ApiResult();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
//        if (code == BaseErrorCode.SUCCESS.getCode()) {
//            return apiResult;
//        } else {
//            throw new ApiResultException(apiResult);
//        }
        return apiResult;
    }

    public boolean isOk() {
        return BaseErrorCode.SUCCESS.getCode() == this.code;
    }

    public static <T> ApiResult<T> feignFail() {
        return failed((IErrorCode)BaseErrorCode.FEIGN_FAIL);
    }

    public long getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

    public T getData() {
        return this.data;
    }

    public void setCode(final long code) {
        this.code = code;
    }

    public void setMsg(final String msg) {
        this.msg = msg;
    }

    public void setData(final T data) {
        this.data = data;
    }

}
